package com.qm.datax;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/*
* 将ck最新ddl
* */
public class ClickHouseDDLExporter {
    // 配置数据库连接信息
    private static final String JDBC_URL = "jdbc:clickhouse://192.168.105.243:8123/px_ads";
    private static final String USERNAME = "default";
    private static final String PASSWORD = "69LTVnuF";
    private static final String OUTPUT_DIR = "D:/ddl_scripts/"; // 输出目录

    public static void main(String[] args) {
        Connection conn = null;
        try {
            // 1. 注册驱动（新版本ClickHouse JDBC驱动自动注册）

            // 2. 获取数据库连接
            conn = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);

            // 3. 获取所有表名
            List<String> tableNames = getTableNames(conn);

            // 4. 遍历生成建表语句
            for (String tableName : tableNames) {
                String ddl = getTableDDL(conn, tableName);
                saveToFile(tableName, ddl);
            }

            System.out.println("成功导出 " + tableNames.size() + " 个表的DDL语句");

        } catch (SQLException | IOException e) {
            System.err.println("程序执行出错: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 5. 关闭数据库连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    // 获取所有表名
    private static List<String> getTableNames(Connection conn) throws SQLException {
        List<String> tables = new ArrayList<>();
        String sql = "SELECT name FROM system.tables WHERE database = 'px_ads'";

        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                tables.add(rs.getString("name"));
            }
        }
        return tables;
    }

    // 获取单个表的DDL语句
    private static String getTableDDL(Connection conn, String tableName) throws SQLException {
        String ddl = "";
        String sql = "SHOW CREATE TABLE " + tableName;

        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            if (rs.next()) {
                ddl = rs.getString(1);
            }
        }
        return ddl;
    }

    // 保存到文件
    private static void saveToFile(String tableName, String ddl) throws IOException {
        String fileName = OUTPUT_DIR + tableName + ".sql";

        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(ddl);
            writer.write(";"); // 添加分号结尾
            System.out.println("已生成: " + fileName);
        }
    }
}